package com.chungkui.bond.oauth2.server.controller;

import com.chungkui.bond.authmanager.bean.Client;
import com.chungkui.bond.common.core.api.ResBus;
import com.chungkui.bond.oauth2.server.service.ClientService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/oauth")
public class Oauth2Controller {
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private ClientService clientService;
    @DeleteMapping("/logout")
    public ResBus<?> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader)
    {
        if (StringUtils.isEmpty(authHeader))
        {
            return ResBus.success();
        }

        String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
        if (accessToken == null || StringUtils.isEmpty(accessToken.getValue()))
        {
            return ResBus.success();
        }
        // 清空 access token
        tokenStore.removeAccessToken(accessToken);
        // 清空 refresh token
        OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
        tokenStore.removeRefreshToken(refreshToken);

        return ResBus.success();
    }
    @DeleteMapping("/logoutByUsername")
    public ResBus<?> logoutByUsername(@RequestParam(value ="username") String username)
    {
        if (StringUtils.isEmpty(username))
        {
            return ResBus.success();
        }
        List <Client> clients=clientService.list();
        if(CollectionUtils.isNotEmpty(clients)){
            for(Client client:clients){
                Collection<OAuth2AccessToken> tokens= tokenStore.findTokensByClientIdAndUserName(client.getClientId(),username);
                for(OAuth2AccessToken oAuth2AccessToken:tokens){
                    tokenStore.removeAccessToken(oAuth2AccessToken);
                    tokenStore.removeRefreshToken(oAuth2AccessToken.getRefreshToken());
                }
            }
        }
        return ResBus.success();
    }
}
